var app = getApp()  
Page({  
  data: {  
    navbar: ['发布闲置', '发布图书'],  
    fenlei:[],
    jichengxin:['全新','一成新','二成新','三成新','四成新','五成新','六成新','七成新','八成新','九成新'],
    jichengxinindex:0,
    currentTab: 0,
    index:0,
    uploadimages:[],
    isQuanXin:'全新',
    //书籍字段
    book_name:'',
    page_num:'',
    book_type:'',
    press:'',
    remark:'',
    cover_img:'',
    catalog_img1:'',
    catalog_img2:'',
    catalog_img3:'',
    text_img1:'',
    text_img2:'',
    text_img3:'',
    text_img4:'',
    book_address:'',
    transaction_address1:'',
    transaction_address2:'',
    transaction_address3:'',
    rent:'',
    original_price:'',
      author:'',
    //闲置字段
    unuse_name:'',
    unuse_info:'',
    unuse_address:'',
    unuse_type:'',
    price:'',
    original_price:'',
    is_free_post:0,
    freight:'',
    isShowJianPan:0,
    address:{},
    userInfo:{},

    imageLimit:1,
    id:0,
      show:true,
      ispush:0,
  },
  navbarTap: function(e){
      wx.clearStorageSync();
    this.setData({  
      currentTab: e.currentTarget.dataset.idx,
        unuse_type:''
    })
      app.globalData.pushType = e.currentTarget.dataset.idx;
  },
  bindPickerChange:function(e){
  	var that = this;
  	that.setData({
        book_type:that.data.fenlei[e.detail.value].btype,
        index:e.detail.value
  	})
  },
  //切换几成新
  bindPickerChangeUnusetype:function(e){
    var that = this;
    // console.log(that.data.jichengxin[e.detail.value])
    that.setData({
        isQuanXin:that.data.jichengxin[e.detail.value],
        jichengxinindex:e.detail.value
    })
  },
  onLoad:function(e){
      var that = this;
    app.editTabBar();
    wx.clearStorageSync();
    this.getXiaoShuoType();
      var unuse_type = wx.getStorageSync('unuse_type');
      this.setData({
          unuse_type:unuse_type,
          address:app.globalData.address,
          userInfo:app.globalData.userInfo,
          currentTab:1,
          is_free_post:1
      })
      this.setData({
          book_address:that.data.address.city+that.data.address.district + that.data.address.township
      })
    if(0 == this.data.id){
        this.setData({
            currentTab:app.globalData.pushType
        })
    }
    if(undefined != e.id){
      this.setData({
        id:e.id,
        currentTab:e.type
      })
      this.editorData();
    }
    // console.log('12222'+getApp().globalData.userInfo.contract.length)
    //判断是否有手机号信息
    if(null == getApp().globalData.userInfo.contract || getApp().globalData.userInfo.contract.length <= 0){
        wx.showModal({
            title:'提示',
            content:'您还未完善个人资料，请及时完善',
            success: function(res) {
                if (res.confirm) {
                    wx.navigateTo({
                        url: '/pages/my/gereninfo/index'
                    })
                } else if (res.cancel) {
                    console.log('用户点击取消')
                }
            }
        })
        return;
    }

  },

    getXiaoShuoType:function(e){
      var that = this;
        wx.request({
            url: app.data.server+'/index.php/Tongcheng/Book/getDocDicByType?type=xiaoshuostype',
            success:function(d){
                // console.log('123'+JSON.stringify(d.data));
                that.setData({
                    fenlei:d.data,
                    book_type:d.data[0].btype
                })
            }
        })
    },
  onShow:function(e){
    this.setData({
        address:app.globalData.address,
        unuse_type:wx.getStorageSync('unuse_type'),
        ispush:0
    })
      //更新下个人用户信息
      this.setData({
          address:app.globalData.address,
          userInfo:app.globalData.userInfo
      })
    // console.log(this.data.currentTab+','+this.data.id);
  },
  chooseimages:function(e){
    var that = this;
    wx.chooseImage({
        count: that.data.imageLimit, // 默认9
        sizeType: ['compressed'], // 可以指定是原图还是压缩图，默认二者都有
        sourceType: ['album', 'camera'], // 可以指定来源是相册还是相机，默认二者都有
        success: function (res) { 
            // 返回选定照片的本地文件路径列表，tempFilePath可以作为img标签的src属性显示图片
            var tempFilePaths = res.tempFilePaths;
            // console.log(tempFilePaths);
            var j = that.data.uploadimages.length;
            that.uploadDIY(tempFilePaths,getApp().globalData.userInfo.uid,0,j,0,0);
        }
    })
  },
  chooseimages1:function(e){
    var that = this;
    var name = e.currentTarget.dataset.name;
    wx.chooseImage({
        count: 1, // 默认9
        sizeType: ['compressed'], // 可以指定是原图还是压缩图，默认二者都有
        sourceType: ['album', 'camera'], // 可以指定来源是相册还是相机，默认二者都有
        success: function (res) { 
            // 返回选定照片的本地文件路径列表，tempFilePath可以作为img标签的src属性显示图片
            var tempFilePaths = res.tempFilePaths;
            // console.log(tempFilePaths);
            var j = that.data.uploadimages.length;
            wx.uploadFile({  
                  url: app.data.server + '/index.php/Tongcheng/Book',   
                  filePath: tempFilePaths[0],  
                  name: 'file',  
                  formData:{  
                    
                  },  
                  success: (res) => {  
                    var jsonData = JSON.parse(res.data);
                    switch(name){
                      case 'cover_img':
                        that.setData({
                          cover_img:JSON.parse(jsonData).filename
                        })
                      break;
                      case 'catalog_img1':
                        that.setData({
                          catalog_img1:JSON.parse(jsonData).filename
                        })
                      break;
                      case 'catalog_img2':
                        that.setData({
                          catalog_img2:JSON.parse(jsonData).filename
                        })
                      break;
                      case 'catalog_img3':
                        that.setData({
                          catalog_img3:JSON.parse(jsonData).filename
                        })
                      break;
                      case 'text_img1':
                        that.setData({
                          text_img1:JSON.parse(jsonData).filename
                        })
                      break;
                      case 'text_img2':
                        that.setData({
                          text_img2:JSON.parse(jsonData).filename
                        })
                      break;
                      case 'text_img3':
                        that.setData({
                          text_img3:JSON.parse(jsonData).filename
                        })
                      break;
                      case 'text_img4':
                        that.setData({
                          text_img4:JSON.parse(jsonData).filename
                        })
                      break;
                    }
                  },  
                  fail: (res) => {  
                    // failUp++;
                  }  
            }) 
        }
    })
  },
  uploadDIY:function(filePaths,uid,i,j,successUp,failUp){  
      var length = filePaths.length;
      var that = this;
      wx.uploadFile({  
          url: app.data.server + '/index.php/Tongcheng/Book',   
          filePath: filePaths[i],  
          name: 'file',  
          formData:{  
            'uid': uid,
            'index':j
          },  
          success: (res) => {  
            console.log(res.data)
            var jsonData = JSON.parse(res.data);
            that.data.uploadimages[j] = JSON.parse(jsonData);
            //设置下全局的上传图片对象
            getApp().globalData.uploadimages[j] = JSON.parse(jsonData);
            that.setData({
              uploadimages:that.data.uploadimages
            })
            console.log(that.data.uploadimages[j].filename)
            successUp++;
          },  
          fail: (res) => {  
            failUp++;
          },  
          complete: (res) => {  
              i ++; 
              j++;                         
              if(i == length)  
              {                        
                wx.showToast({
                  title:'总共'+successUp+'张上传成功,'+failUp+'张上传失败！'
                });  
              }  
              else  
              {  //递归调用uploadDIY函数  

                  that.uploadDIY(filePaths,uid,i,j,successUp,failUp); 
              }  
          },  
    }) 
  },  
  //切换全新
  quanXinSl:function(e){
    this.setData({
      isQuanXin:this.data.isQuanXin==0?1:0
    })
  },
  toFenLei:function(e){
      var type = e.currentTarget.dataset.type;
    wx.navigateTo({
      url:'/pages/push/fenlei?type='+type
    })
  },
  formSubmmit:function(e){
      if(null == getApp().globalData.userInfo.contract || getApp().globalData.userInfo.contract.length <= 0){
          wx.showModal({
              title:'提示',
              content:'您还未完善个人资料，请及时完善',
              success: function(res) {
                  if (res.confirm) {
                      wx.navigateTo({
                        url: '/pages/my/gereninfo/index'
                      })
                  } else if (res.cancel) {
                      console.log('用户点击取消')
                  }
              }
          })
          return;
      }
    // console.log(this.data)
      var that = this;
      if(that.data.page_num<=0){
          wx.showToast({
              title:'请正确填写页数',
              icon: 'none',
              duration: 2000
          })
          return;
      }
      if(''==that.data.book_name){
          wx.showToast({
              title:'请填写书名',
              icon: 'none',
              duration: 2000
          })
          return;
      }

      if(that.data.cover_img == ''){
          wx.showToast({
              title:'请选择封面',
              icon: 'none',
              duration: 2000
          })
          return;
      }
      if(that.data.rent <= 0){
          wx.showToast({
              title:'请填写正确租金',
              icon: 'none',
              duration: 2000
          })
          return;
      }
      if(that.data.original_price <= 0){
          wx.showToast({
              title:'请填写正确原价',
              icon: 'none',
              duration: 2000
          })
          return;
      }
      if(that.data.rent < that.data.original_price*0.01 || that.data.rent > that.data.original_price*0.02){
          wx.showToast({
              title:'租金在原价的1%-2%,不得多余2%',
              icon: 'none',
              duration: 2000
          })
          return;
      }
      that.setData({
          ispush:1
      })
    wx.request({
      url: app.data.server + '/index.php/Tongcheng/Book/add', 
      data: {
         formData:JSON.stringify(this.data)
      },
      header: {'content-type': 'application/x-www-form-urlencoded'},
      method:'POST',
      dataType:'json',
      success: function(res) {
        console.log(res.data)
        if(1 == res.data){
          wx.showToast({
            title:'发布成功',
            icon: 'success',
            duration: 2000
          })
            setTimeout(function(){
                wx.redirectTo({
                  url: '/pages/find/find'
                })
            },2000)
        }else{
          wx.showToast({
            title:'发布失败',
            icon: 'fail',
            duration: 2000
          })
        }
      }
    })
  },
  formSubmmit1:function(e){
      if(null == getApp().globalData.userInfo.contract || getApp().globalData.userInfo.contract.length <= 0){
          wx.showModal({
              title:'提示',
              content:'您还未完善个人资料，请及时完善',
              success: function(res) {
                  if (res.confirm) {
                      wx.navigateTo({
                          url: '/pages/my/gereninfo/index'
                      })
                  } else if (res.cancel) {
                      console.log('用户点击取消')
                  }
              }
          })
          return;
      }
    // console.log(this.data)
      var that = this;
      if(''==that.data.unuse_name){
          wx.showToast({
              title:'请填写宝贝名称',
              icon: 'none',
              duration: 2000
          })
          return;
      }

      if(that.data.uploadimages.length<=0){
          wx.showToast({
              title:'请至少选择一张图片',
              icon: 'none',
              duration: 2000
          })
          return;
      }
      if(that.data.price <= 0){
          wx.showToast({
              title:'请正确填写价格',
              icon: 'none',
              duration: 2000
          })
          return;
      }
      if(that.data.original_price <= 0){
          wx.showToast({
              title:'请正确填写原价',
              icon: 'none',
              duration: 2000
          })
          return;
      }
      if(parseFloat(that.data.original_price) < parseFloat(that.data.price)){
          wx.showToast({
              title:'请正确填写价格',
              icon: 'none',
              duration: 2000
          })
          return;
      }
      that.setData({
          ispush:1
      })
    wx.request({
      url: app.data.server + '/index.php/Tongcheng/Book/addXianZhi', 
      data: {
         formData:JSON.stringify(this.data)
      },
      header: {'content-type': 'application/x-www-form-urlencoded'},
      method:'POST',
      dataType:'json',
      success: function(res) {
        console.log(res.data)
        if(1 == res.data){
          wx.showToast({
            title:'发布成功',
            icon: 'success',
            duration: 2000
          })
            setTimeout(function(){
                wx.redirectTo({
                    url: '/pages/index/index'
                })
            },2000)
        }else{
          wx.showToast({
            title:'发布失败',
            icon: 'fail',
            duration: 2000
          })
        }
      }
    })
  },
  formSetValue:function(e){
    var that = this;
    var name = e.currentTarget.dataset.name;
    switch(name){
        case 'book_name':
          that.setData({
            book_name:e.detail.value
          })
        break;
        case 'page_num':
          that.setData({
            page_num:e.detail.value
          })
        break;
        case 'book_type':
          that.setData({
            book_type:e.detail.value
          })
        break;
        case 'press':
          that.setData({
            press:e.detail.value
          })
        break;
        case 'book_address':
          that.setData({
            book_address:e.detail.value
          })
        break;
        case 'transaction_address1':
          that.setData({
            transaction_address1:e.detail.value
          })
        break;
        case 'transaction_address2':
          that.setData({
            transaction_address2:e.detail.value
          })
        break;
        case 'transaction_address3':
          that.setData({
            transaction_address3:e.detail.value
          })
        break;
        case 'rent':
          that.setData({
            rent:e.detail.value
          })
        break;
        case 'original_price':
          that.setData({
            original_price:e.detail.value
          })
        break;
        case 'author':
            that.setData({
                author:e.detail.value
            })
            break;
        case 'remark':
            that.setData({
                remark:e.detail.value
            })
            break;



        //闲置字段
        case 'unuse_name':
          that.setData({
            unuse_name:e.detail.value
          })
        break;
        case 'unuse_info':
          that.setData({
            unuse_info:e.detail.value
          })
        break;
        case 'unuse_address':
          that.setData({
            unuse_address:e.detail.value
          })
        break;
        case 'is_new':
          that.setData({
            is_new:e.detail.value
          })
        break;
        // case 'unuse_type':
        //   that.setData({
        //     unuse_type:e.detail.value
        //   })
        // break;
        case 'price':
          that.setData({
            price:e.detail.value
          })
        break;
        case 'original_price':
          that.setData({
            original_price:e.detail.value
          })
        break;
        case 'is_free_post':
          that.setData({
            is_free_post:e.detail.value
          })
        break;
        case 'freight':
          that.setData({
            freight:e.detail.value
          })
        break;
    }
  },
    // clear:function(e){
    //     event.detail
    // },
  showJianPan:function(e){
    var that = this;
    this.setData({
      isShowJianPan:that.data.isShowJianPan==1?0:1
    })
      this.setData({
          show:that.data.isShowJianPan==1?false:true
      })
  },
  changeBaoYou:function(e){
    var that = this;
    that.setData({
      is_free_post:that.data.is_free_post==1?0:1

    })
      if(1==this.data.is_free_post){
        that.setData({
            freight:0
        })
      }
  },
  toCity:function(e){
    wx.navigateTo({
      url:'/pages/wx-index-list/city'
    })
  },
  //获取上传信息进行编辑
  editorData:function(e){
    var that = this;
    var id = this.data.id;
    if(0 != id){
      var url = app.data.server + '/index.php/Tongcheng/Book/getBookInfo?id='+id;
      if(0 == this.data.currentTab){
        url = app.data.server + '/index.php/Tongcheng/Book/getUnuseInfo?id='+id;
      }
      wx.request({
      url: url, 
      success: function(res) {
        console.log(res.data)
        if(0 == that.data.currentTab){
          that.setData({
            //闲置字段
            unuse_name:res.data.unuse_name,
            unuse_info:res.data.unuse_info,
            unuse_address:res.data.unuse_address,
            unuse_type:res.data.unuse_type,
            price:res.data.price,
            original_price:res.data.original_price,
            is_free_post:res.data.is_free_post,
            freight:res.data.freight,
            unuse_type:res.data.unuse_type
          })
      }else {
        that.setData({
            //书籍字段
            book_name:res.data.book_name,
            page_num:res.data.page_num,
            book_type:res.data.book_type,
            press:res.data.press,
            remark:res.data.remark,
            cover_img:res.data.cover_img,
            catalog_img1:res.data.catalog_img1,
            catalog_img2:res.data.catalog_img2,
            catalog_img3:res.data.catalog_img3,
            text_img1:res.data.text_img1,
            text_img2:res.data.text_img2,
            text_img3:res.data.text_img3,
            text_img4:res.data.text_img4,
            book_address:res.data.book_address,
            transaction_address1:res.data.transaction_address1,
            transaction_address2:res.data.transaction_address2,
            transaction_address3:res.data.transaction_address3,
            rent:res.data.rent,
            original_price:res.data.original_price,
              author:res.data.author
          })
      }
        
      }
    })
    }
  },
    //删除图片
    delimage:function(e){
      var indexold = e.currentTarget.dataset.index;
      var that = this;
      console.log('index==='+e.currentTarget.dataset.index);
        var upimages = that.data.uploadimages;
        var newUpimage = [];
        upimages.forEach(function(item,index){
            console.log(JSON.stringify(item)+'----------'+index);
            if(parseInt(indexold) != parseInt(index)){
                newUpimage.push(item);
            }
        })
        that.setData({
            uploadimages:newUpimage
        })
    }
})

